package com.simple.system.service;
import com.simple.system.entity.SysUser;
import com.simple.system.repository.SysUserRepository;
import com.simple.system.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;


@Service
public class SysUserService {
    @Autowired
    private SysUserRepository userRepository;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${password.error.max.attempts:3}")
    private int maxAttempts;

    @Value("${password.error.lock.time:10}")
    private long lockTime;

    public SysUser saveUser(SysUser user) {
        SysUser savedUser = userRepository.save(user);
        redisTemplate.opsForValue().set("user:" + savedUser.getId(), savedUser, 1, TimeUnit.HOURS);
        return savedUser;
    }

    public SysUser getUserById(Long id) {
        SysUser user = (SysUser) redisTemplate.opsForValue().get("user:" + id);
        if (user == null) {
            user = userRepository.findById(id).orElse(null);
            if (user != null) {
                redisTemplate.opsForValue().set("user:" + id, user, 1, TimeUnit.HOURS);
            }
        }
        return user;
    }

    public List<SysUser> getAllUsers() {
        return userRepository.findAll();
    }

    public SysUser getUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }

    public void disableUser(Long id) {
        Optional<SysUser> userOptional = userRepository.findById(id);
        userOptional.ifPresent(user -> {
            // 这里可以添加禁用用户的逻辑，例如标记用户为禁用状态
        });
    }

    public boolean validatePassword(String username, String password) {
        String key = "password:error:" + username;
        if (redisUtil.hasKey(key)) {
            int attempts = (int) redisUtil.get(key);
            if (attempts >= maxAttempts) {
                return false;
            }
        }

        SysUser user = userRepository.findByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            redisUtil.delete(key);
            return true;
        } else {
            if (redisUtil.hasKey(key)) {
                redisUtil.increment(key);
            } else {
                redisUtil.set(key, 1, lockTime, TimeUnit.MINUTES);
            }
            return false;
        }
    }

    public RedisUtil getRedisUtil() {
        return redisUtil;
    }

    public int getMaxAttempts() {
        return maxAttempts;
    }

}
